#include <iostream>
#include <unistd.h>
#include <pthread.h>
// 与mutex类似
pthread_mutex_t mutex;
// pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
pthread_cond_t cond;
int ticket = 0;
void *active(void *args)
{
    std::string name = static_cast<const char *>(args);
    while (true)
    {
        pthread_mutex_lock(&mutex);
        while (ticket == 0) // 一定要循环判断条件是否满足,否则会出现虚假唤醒
        {
            pthread_cond_wait(&cond, &mutex);
        }
        // 满足条件,访问公共资源
        std::cout << name << "get a ticket" << --ticket << std::endl;
        pthread_mutex_unlock(&mutex);
        usleep(1000);
    }
    return nullptr;
}
int main()
{
    pthread_t th1, th2, th3;
    pthread_create(&th1, nullptr, active, (void *)"thread-1");
    pthread_create(&th2, nullptr, active, (void *)"thread-2");
    pthread_create(&th3, nullptr, active, (void *)"thread-3");
    while(true)
    {
        sleep(1);
        ticket+=10;
        pthread_cond_signal(&cond);
        //广播式唤醒
    }
    pthread_join(th1,nullptr);
    pthread_join(th2,nullptr);
    pthread_join(th3,nullptr);
    return 0;
}